package com.silverhaze.diamond.client.ui.panel;

import com.silverhaze.diamond.client.ui.dialogs.AbstractDialog;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * SystemUser: Ivan Babanin
 * Date: 13.08.2007
 * Time: 0:41:50
 * This code is part of lizard Project.
 * Strictly confidential.
 */
public class ErrorPanel extends JPanel {
    private static final int BORDER_EPSILON = 15;

    private List<JLabel> labels;
    private AbstractDialog abstractDialog;

    public ErrorPanel(AbstractDialog abstractDialog) {
        setLayout(new BorderLayout());
        setBorder(new TitledBorder(" Ошибка "));

        labels = new ArrayList<JLabel>();
        this.abstractDialog = abstractDialog;

        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                ErrorPanel.this.clearErrorText();
            }
        });

        clearErrorText();
    }

    public void clearErrorText() {
        getLabels().clear();
        removeAll();

        setVisible(false);
        abstractDialog.pack();
    }

    private List<String> divideIntoSuitableStrings(String text) {
        List<String> resultList = new ArrayList<String>();
        FontMetrics fontMetrics = getFontMetrics(new JLabel().getFont());

        int i = 0;
        int width = abstractDialog.getWidth();

        String[] textWords = text.split("\\s");
        StringBuilder builder = new StringBuilder();

        while (i < textWords.length) {
            StringBuilder temp = new StringBuilder(builder.toString());
            temp.append(textWords[i]).append(" ");

            if (fontMetrics.stringWidth(temp.toString()) + BORDER_EPSILON > width) {
                resultList.add(builder.toString());
                builder = new StringBuilder();
            } else {
                builder.append(textWords[i++]);
                if (i != textWords.length) {
                    builder.append(" ");
                }
            }
        }

        if (builder.toString().length() != 0) {
            resultList.add(builder.toString());
        }

        return resultList;
    }

    public void setErrorText(String errorText) {
        List<String> stringText = divideIntoSuitableStrings(errorText);

        clearErrorText();

        Box vBox = Box.createVerticalBox();
        for (String str : stringText) {
            JLabel label = new JLabel(str);
            label.setForeground(Color.RED);

            getLabels().add(label);
            vBox.add(label);
            vBox.add(Box.createVerticalStrut(3));
        }

        setVisible(true);
        add(vBox, BorderLayout.CENTER);
        abstractDialog.pack();
    }

    public List<JLabel> getLabels() {
        return labels;
    }
}

